const express = require('express');
const { Op, where } = require('sequelize');
const { Chapter, Course } = require('../../models');
const router = express.Router();
const { chaptersFilterBody } = require('../../utils/filter-req');
const { success, failure } = require('../../utils/responses');
const { NotFound } = require('http-errors');
const getList = async (req) => {
  const { id } = req.params;
  const chapter = await Chapter.findByPk(id, getCondition());
  if (!chapter) {
    throw new NotFound(`ID：${id}不存在`);
  }
  return chapter;
};
const getCondition = () => {
  return {
    attributes: { exclude: ['CourseId'] },
    include: [{ model: Course, as: 'course', attributes: ['id', 'name'] }],
  };
};
router.get('/', async (req, res) => {
  try {
    let { courseId, title, currentPage, pageSize } = req.query;
    if (!courseId) {
      throw BadRequest('获取章节列表失败，课程ID不能为空。');
    }
    pageSize = Math.abs(Number(pageSize || 10));
    currentPage = Math.abs(Number(currentPage || 1));
    const condition = {
      //还有要注意这里的order，这里出现了两个排序。要先按照rank字段，从小到大排序。如果出现了两个相同的rank值，那也没关系，那就用id来从小到大来排序。
      order: [
        ['rank', 'ASC'],
        ['id', 'ASC'],
      ],

      ...getCondition(),
      limit: pageSize,
      offset: (currentPage - 1) * pageSize,
    };
    condition.where = {
      courseId: {
        [Op.eq]: courseId,
      },
    };

    if (title) {
      condition.where = {
        title: {
          [Op.like]: `%${title}%`,
        },
      };
    }

    const { count, rows } = await Chapter.findAndCountAll(condition);

    const data = {
      data: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    };
    success({
      res,
      data,
    });
  } catch (error) {
    // 返回错误信息
    failure({ res, error });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const chapter = await getList(req);
    success({ res, data: chapter });
  } catch (error) {
    failure({ res, error });
  }
});
router.post('/', async (req, res) => {
  try {
    const body = chaptersFilterBody(req.body);

    const chapter = await Chapter.create(body);
    await Course.increment('chaptersCount', { where: { id: chapter.courseId } });
    //200状态么和201不同， 201表示请求成功并且创建新的资源 更专业
    success({ res, code: 201, message: '创建成功' });
  } catch (error) {
    failure({ res, error, message: '创建失败' });
  }
});
router.delete('/:id', async (req, res) => {
  try {
    const chapter = await getList(req);
    // const count = await Chapter.count({ where: { courseeId: req.params.id } })

    // if (count > 0) {
    //     throw BadRequest('当前章节有课程，无法删除')
    // }

    //删除
    await chapter.destroy();
    await Course.decrement('chaptersCount', { where: { id: chapter.courseId } });

    success({ res, message: '删除成功' });
  } catch (error) {
    failure({ res, error, message: '删除失败' });
  }
});

router.put('/:id', async (req, res) => {
  try {
    const chapter = await getList(req);
    const body = chaptersFilterBody(req.body);
    await chapter.update(body);
    success({ res, message: '更新成功' });
  } catch (error) {
    failure({ res, error });
  }
});

module.exports = router;
